package com.vanysoft.framework.exception;

import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.BaseResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

@ControllerAdvice
public class BaseResponseAdvice implements ResponseBodyAdvice<BaseResponse> {
    private final Log log = LogFactory.getLog(getClass());

    @Resource
    private MessageSource messageSource;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return BaseResponse.class.isAssignableFrom(returnType.getMethod().getReturnType());
    }

    @Override
    public BaseResponse beforeBodyWrite(BaseResponse body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (StringUtils.isEmpty(body.getRspCode())) {
            body.setRspCode(MessageCodeConstant.RTN_CODE_SUCCESS);
        }
        if (StringUtils.isEmpty(body.getRspMsg())) {
            body.setRspMsg(messageSource.getMessage(body.getRspCode(), null, LocaleContextHolder.getLocale()));
        }
        return body;
    }
}